#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
快速启动程序 - 主入口文件
支持多模式软件快速启动，具有图形化界面
遵循KISS、YAGNI、SOLID设计原则

Copyright (c) 2025 RAYA-MAX
Quick-Start is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan
PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""

import sys
import os
import tkinter as tk
from tkinter import messagebox

# 添加当前目录到Python路径，确保能导入自定义模块
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

try:
    from main_window import MainWindow
except ImportError as e:
    print(f"导入模块失败: {e}")
    print("请确保所有必需的文件都在同一目录下")
    sys.exit(1)


def check_dependencies():
    """
    检查程序依赖
    
    Returns:
        bool: 依赖是否满足
    """
    try:
        import tkinter
        import json
        import subprocess
        import threading
        return True
    except ImportError as e:
        print(f"缺少必需的依赖: {e}")
        return False


def setup_exception_handler():
    """设置全局异常处理器"""
    def handle_exception(exc_type, exc_value, exc_traceback):
        if issubclass(exc_type, KeyboardInterrupt):
            # 允许Ctrl+C正常退出
            sys.__excepthook__(exc_type, exc_value, exc_traceback)
            return
        
        # 显示错误对话框
        error_msg = f"程序发生未处理的错误:\n\n{exc_type.__name__}: {exc_value}"
        
        try:
            root = tk.Tk()
            root.withdraw()  # 隐藏主窗口
            messagebox.showerror("程序错误", error_msg)
            root.destroy()
        except:
            # 如果GUI不可用，输出到控制台
            print(error_msg)
        
        # 调用默认异常处理器
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
    
    sys.excepthook = handle_exception


def create_default_config():
    """创建默认配置文件（如果不存在）"""
    config_file = "config.json"
    if not os.path.exists(config_file):
        try:
            from config_manager import ConfigManager
            # ConfigManager会自动创建默认配置
            config_manager = ConfigManager()
            print("已创建默认配置文件")
        except Exception as e:
            print(f"创建默认配置失败: {e}")
            return False
    return True


def main():
    """主函数"""
    print("快速启动程序 v1.0")
    print("正在初始化...")
    
    # 检查依赖
    if not check_dependencies():
        print("依赖检查失败，程序退出")
        return 1
    
    # 设置异常处理
    setup_exception_handler()
    
    # 创建默认配置
    if not create_default_config():
        print("配置初始化失败，程序退出")
        return 1
    
    try:
        # 创建并运行主窗口
        print("启动图形界面...")
        app = MainWindow()
        app.run()
        
    except Exception as e:
        error_msg = f"程序启动失败: {e}"
        print(error_msg)
        
        try:
            root = tk.Tk()
            root.withdraw()
            messagebox.showerror("启动失败", error_msg)
            root.destroy()
        except:
            pass
        
        return 1
    
    print("程序正常退出")
    return 0


if __name__ == "__main__":
    # 设置工作目录为程序所在目录（支持exe文件）
    if getattr(sys, 'frozen', False):
        # 如果是打包后的exe文件
        app_dir = os.path.dirname(sys.executable)
    else:
        # 如果是Python脚本
        app_dir = os.path.dirname(os.path.abspath(__file__))

    os.chdir(app_dir)

    # 运行主程序
    exit_code = main()
    sys.exit(exit_code)
